package com.sunsharing.transport.netty;

import com.sunsharing.common.URL;
import com.sunsharing.common.anno.Factory;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.ConnectClients;
import com.sunsharing.transport.IoHandle;
import com.sunsharing.transport.Server;
import com.sunsharing.transport.mina.MinaChannel;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ClassResolvers;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-23
 * Time: 上午9:54
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="NETTY")
public class NettyServer implements Server {
    ServerBootstrap bootstrap = null;
    Logger logger = Logger.getLogger(NettyServer.class);
    @Override
    public void startServer(final URL url, final IoHandle ioHandle) {
        int port = url.getPort();
        bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newFixedThreadPool(20),
                        Executors.newFixedThreadPool(20)));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        new ObjectEncoder(),
                        new ObjectDecoder(
                                ClassResolvers.cacheDisabled(getClass().getClassLoader())),
                        new ObjectEchoServerHandler(ioHandle,url));
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
        logger.info("Netty服务在"+port+"端口启动监听");
    }

    @Override
    public void stopServer() {
        bootstrap.releaseExternalResources();
    }


}
